package com.control;

import com.dao.UserDao;
import com.dao.UserDaoImpl;
import com.model.User;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/register.do")
public class RegisterServlet extends HttpServlet {
    //用户注册合法性检测,并返回错误信心
    private boolean isRight(User user, StringBuilder errorMassage) {
        boolean iserror = false;
        if (user.getUsername().isEmpty()) {
            errorMassage.append("账户名不能为空<br>");
            iserror = true;
        }
        if (user.getPasswd().isEmpty()) {
            errorMassage.append("密码不能为空<br>");
            iserror = true;
        }
        UserDao userDao = new UserDaoImpl();
        if (userDao.hasUser(user)) {
            errorMassage.append("用户已存在<br>");
            iserror = true;
        }
        if (iserror == true) {
            return false;
        }
        return true;
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = (String) request.getParameter("username");
        String passwd = (String) request.getParameter("passwd");
        User user = new User();
        user.setUsername(username);
        user.setPasswd(passwd);
        StringBuilder errorMassage = new StringBuilder();
        if (isRight(user, errorMassage)) {
            UserDao userDao = new UserDaoImpl();
            userDao.addUser(user);
            response.sendRedirect("rSuccess.jsp");
        } else {
            request.setAttribute("errorMassage", errorMassage);
            RequestDispatcher requestDispatcher = request.getRequestDispatcher("register.jsp");
            requestDispatcher.forward(request, response);
        }
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.sendRedirect("register.jsp");
    }
}
